package gxprod.androidai.functions;

import gxprod.androidai.BubbleAdapter;
import gxprod.androidai.regex.MatchResult;
import gxprod.androidai.regex.NamedMatcher;
import gxprod.androidai.regex.NamedPattern;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;

/**
 * Represents a set of similar actions the user can request.
 * @author Josh Maleszewski
 */
public abstract class Function {

	public static final String getDescription() { return "Unnamed Function"; }
	/**
	 * Filters out commands in a quick efficient way. for example, checking for keywords and sentences that are 
	 * too short or long to fit this command. Shouldn't involve regular expressions or string manipulation
	 * @param command
	 * 		the command to be compared
	 * @return
	 * false if the given command couldn't fit this function, true if it might.
	 */	
	public abstract boolean cullFunction(String command);
	public abstract MatchResult isMatch(String statement);
	public abstract boolean execute(MatchResult match, BubbleAdapter adapter);

	public static String TAG(Object t) { return t.getClass().getSimpleName(); }
	
	public MatchResult isMatch(String statement, NamedPattern[] NamedPatterns, float confidence) {
		NamedMatcher matcher;
		for(int i = 0; i < NamedPatterns.length; i++) {
			matcher = NamedPatterns[i].matcher(statement);
			if(matcher.find()) 
				return new MatchResult(matcher, i, confidence, this);
		}
		return new MatchResult();
	}

	/**\
	 * Returns a StringBuffer with the contents of the file at the given URL.
	 * If it fails, null is returned.
	 */
	public static BufferedReader fetch(String url) {
		try {
			return new BufferedReader(new InputStreamReader(new URL(url).openStream()));
		} catch(Exception ex) {
			return null;
		}
	}

	/**
	 * Doesnt work yet
	 * @param query
	 * @return
	 */
	public static String getWikiSniplet(String query) {
		query = query.replace(" ", "+");
		BufferedReader br = Function.fetch("http://en.wikipedia.org/w/api.php?action=query&format=xml&list=search&srsearch=" + query);
		if(br == null)
			return null;
		String line;
		try {
			line = br.readLine();
			while (line != null) {
				if(line.contains("<p ns=")) {
					int begin = line.indexOf("snippet=\"");
					begin += 8;
					int end = line.indexOf("\" size=\"");

					line = line.substring(begin, end - begin);

					line = line.replace("&lt;", "");
					line = line.replace("&gt;", "");
					line = line.replace("&#039;", "\"");

					line = line.replaceAll("span class=\"*\"", "");
					line = line.replace("/span", "");
				}
				line = br.readLine();
			}
			return null;
		} catch (IOException e) {
			return null;
		}
	}
}
